﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TrainingsApp.WebModel;
using System.Web.Services;
using System.Web.Script.Services;
using TrainingsApp.Helper;
using TrainingsApp.Model;
using TrainingsApp.Logic;

namespace TrainingsApp.IPADApp.Teacher2
{
    public partial class Previews : AccountPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public override WebModel.Other.AccountMenuType MenuType
        {
            get { return WebModel.Other.AccountMenuType.Preview; }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
        public static string GetPriviewList(long ChapterId, int ClassId, int iPageIndex, int iPageSize)
        {
            int iRowCount, iPageCount = -1;
            bool boolIsSucess = true;
            string strBackMessage = string.Empty;
            TS_Preview_Collecion pList = null;
            if (PassPort.IsAuthenticated)
            {
                try
                {
                    Dictionary<string, object> dict = new Dictionary<string, object>();
                    dict.Add("UserId", PassPort.CurrentUser.UserID);
                    dict.Add("ChapterId", ChapterId);
                    dict.Add("ClassId", ClassId);
                    pList = TS_Preview_Logic.TS_Preview_ListByPaging(dict, iPageSize, iPageIndex);
                    if (pList != null && pList.TotalCount > 0)
                    {
                        long resultCount = 0;
                        foreach (TS_Preview_Entity entity in pList.TS_Preview_List)
                        {
                            entity.resultList = TS_Preview_Result_Logic.TS_Preview_Result_GetTypicalByPreviewId2(entity.PreviewId.Value, out resultCount);
                            TS_Preview_Result_Entity noGroup = entity.resultList.FirstOrDefault(a => a.GroupId == 99);
                            if (noGroup != null)
                            {
                                entity.resultList.Remove(noGroup);
                                entity.resultList.Add(noGroup);
                            }
                            entity.ResultCount = resultCount;
                            foreach (TS_Preview_Result_Entity r in entity.resultList)
                            {
                                r.ResultPercent = Math.Round((r.GroupCount * 100.0 / (entity.ResultCount == 0 ? 1 : entity.ResultCount)), 2);
                                if (r.GroupId == 99)
                                {
                                    r.Result = "其他";
                                }
                            }
                            entity.Percents = entity.resultList.Select(a => a.ResultPercent.ToString()).ToArray();
                        }
                    }
                    iRowCount = pList.TotalCount;
                    //iPageCount = pList.TotalCount % iPageSize == 0 ? pList.TotalCount / iPageSize : pList.TotalCount / iPageSize + 1;
                }
                catch (Exception ex)
                {
                    boolIsSucess = false;
                    strBackMessage = ex.Message.Replace("\r", "").Replace("\n", "");
                }
            }
            else
            {
                boolIsSucess = false;
                strBackMessage = "您已经登录超时，请重新登录系统。";
            }

            return "{" + string.Format("IsSuccess:{0},Msg:'{1}',PageCount:{2},Table:{3}", boolIsSucess.ToString().ToLower(), strBackMessage, iPageCount, JsonHelper.ToStdJson(pList)) + "}";
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
        public static string GetPriviewList2(long ChapterId, int ClassId, int iPageIndex, int iPageSize)
        {
            int iRowCount, iPageCount = -1;
            bool boolIsSucess = true;
            string strBackMessage = string.Empty;
            TS_Preview_Collecion pList = null;
            if (PassPort.IsAuthenticated)
            {
                try
                {
                    Dictionary<string, object> dict = new Dictionary<string, object>();
                    dict.Add("UserId", PassPort.CurrentUser.UserID);
                    dict.Add("ChapterId", ChapterId);
                    dict.Add("ClassId", ClassId);
                    pList = TS_Preview_Logic.TS_Preview_ListByPaging2(dict, iPageSize, iPageIndex);
                    if (pList != null && pList.TotalCount > 0)
                    {
                        long resultCount = 0;
                        foreach (TS_Preview_Entity entity in pList.TS_Preview_List)
                        {
                            entity.resultList = TS_Preview_Result_Logic.TS_Preview_Result_GetTypicalByPreviewId2(entity.PreviewId.Value, out resultCount);
                            TS_Preview_Result_Entity noGroup = entity.resultList.FirstOrDefault(a => a.GroupId == 99);
                            if (noGroup != null)
                            {
                                entity.resultList.Remove(noGroup);
                                entity.resultList.Add(noGroup);
                            }
                            entity.ResultCount = resultCount;
                            foreach (TS_Preview_Result_Entity r in entity.resultList)
                            {
                                r.ResultPercent = Math.Round((r.GroupCount * 100.0 / (entity.ResultCount == 0 ? 1 : entity.ResultCount)), 2);
                                if (r.GroupId == 99)
                                {
                                    r.Result = "其他";
                                }
                            }
                            entity.Percents = entity.resultList.Select(a => a.ResultPercent.ToString()).ToArray();
                        }
                    }
                    iRowCount = pList.TotalCount;
                    //iPageCount = pList.TotalCount % iPageSize == 0 ? pList.TotalCount / iPageSize : pList.TotalCount / iPageSize + 1;
                }
                catch (Exception ex)
                {
                    boolIsSucess = false;
                    strBackMessage = ex.Message.Replace("\r", "").Replace("\n", "");
                }
            }
            else
            {
                boolIsSucess = false;
                strBackMessage = "您已经登录超时，请重新登录系统。";
            }

            return "{" + string.Format("IsSuccess:{0},Msg:'{1}',PageCount:{2},Table:{3}", boolIsSucess.ToString().ToLower(), strBackMessage, iPageCount, JsonHelper.ToStdJson(pList)) + "}";
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
        public static string PreviewAdd(string Question, string PreviewId, long ChapterId, string QuestionId, int ClassId)
        {
            bool boolIsSucess = true;
            string strBackMessage = string.Empty;
            TS_Preview_Entity entity = new TS_Preview_Entity();
            TS_User_Teacher_Entity t = new TS_User_Teacher_Entity();
            if (PassPort.IsAuthenticated)
            {
                try
                {
                    Dictionary<string, object> dict = new Dictionary<string, object>();
                    dict.Add("TeachId", PassPort.CurrentUser.UserID);
                    dict.Add("ClassId", ClassId);
                    dict.Add("ChapterId", ChapterId);

                    TS_TeachMaterials_Chapter_Entity tc = TS_TeachMaterials_Chapter_Logic.TS_TeachMaterials_Chapter_View(ChapterId);
                    int refCount = 0;
                    if (string.IsNullOrEmpty(QuestionId))//发布，非引用
                    {
                        TS_Question_Entity q = TS_Question_Logic.TS_Question_ViewByQuestion(Question);//根据发布问题查看该问题是否发布过
                        if (q == null)//未发布
                        {
                            q = TS_Question_Logic.TS_Question_Add(new TS_Question_Entity()//发布该问题
                            {
                                QuestionId = Guid.NewGuid(),
                                ChapterId = ChapterId,
                                CourseId = tc.CourseId,
                                MaterialsId = tc.MaterialsId,
                                Question = Question,
                                QuestionType = 2
                            });
                        }
                        else//问题已发布
                        {
                            dict["QuestionId"] = q.QuestionId.Value;
                            TS_Preview_Entity p = TS_Preview_Logic.TS_Question_IsPreviewPublish(dict);//该问题是否由此教师在此章节此班发布
                            if (p != null)
                            {
                                throw new Exception("您已经发布了");
                            }
                            else
                            {
                                PreviewId = TS_Preview_Logic.TS_Question_GetFirstPreviewByQuestionId(q.QuestionId.Value);//发布该问题,引用的前概念Id为此问题Id且未被引用过的
                            }
                        }
                        QuestionId = q.QuestionId.Value.ToString();
                    }
                    else//引用前概念，即问题已存在
                    {
                        dict["QuestionId"] = new Guid(QuestionId);
                        TS_Preview_Entity p = TS_Preview_Logic.TS_Question_IsPreviewPublish(dict);//该问题是否由此教师在此章节当前班发布，如发布直接返回错误，不添加其他班级的发布
                        if (p != null)
                        {
                            throw new Exception("您已经发布了");
                        }
                    }

                    if (!string.IsNullOrEmpty(PreviewId))//更新引用次数
                    {
                        TS_Preview_Entity p = TS_Preview_Logic.TS_Preview_View(new Guid(PreviewId));
                        refCount = p.ReferenceCount;

                        p.ReferenceCount = p.ReferenceCount + 1;
                        TS_Preview_Logic.TS_Preview_Update(p);
                    }

                    t = TS_User_Teacher_Logic.TS_User_Teacher_View(PassPort.CurrentUser.UserID).First();

                    List<TS_Class_Entity> Classes = TS_Class_Logic.TS_Class_GetClassesByUserId(PassPort.CurrentUser.UserID);
                    Guid batch = Guid.NewGuid();

                    dict["QuestionId"] = new Guid(QuestionId);
                    Guid batchId = Guid.NewGuid();
                    foreach (TS_Class_Entity c in Classes)
                    {
                        dict["ClassId"] = c.Idx;
                        TS_Preview_Entity p = TS_Preview_Logic.TS_Question_IsPreviewPublish(dict);//判断在此班级中是否已发布过，如发布过不发布，没有发步过继续发布
                        if (p == null)
                        {
                            Guid NewId = Guid.NewGuid();
                            entity = TS_Preview_Logic.TS_Preview_Add(new TS_Preview_Entity()
                            {
                                PreviewId = NewId,
                                ChapterId = ChapterId,
                                ClassId = c.Idx,
                                CourseId = tc.CourseId,
                                MaterialsId = tc.MaterialsId,
                                PublishDate = DateTime.Now,
                                Question = Question,
                                QuestionId = new Guid(QuestionId),
                                ReferenceCount = 0,
                                SchoolId = c.SchoolId,
                                TeachId = PassPort.CurrentUser.UserID,
                                RefBy = string.IsNullOrEmpty(PreviewId) ? NewId : new Guid(PreviewId),
                                Batch = batchId
                            });
                        }
                        if (c.Idx == ClassId)
                        {
                            PreviewId = entity.PreviewId.Value.ToString();
                        }
                    }
                }
                catch (Exception ex)
                {
                    boolIsSucess = false;
                    strBackMessage = ex.Message.Replace("\r", "").Replace("\n", "");
                }
            }
            else
            {
                boolIsSucess = false;
                strBackMessage = "您已经登录超时，请重新登录系统。";
            }
            return "{" + string.Format("IsSuccess:{0},Msg:'{1}',PreviewId:'{2}',QuestionId:'{3}',Name:'{4}',SchoolName:'{5}',TeachId:'{6}',PublishSmallDate:'{7}'", boolIsSucess.ToString().ToLower(), strBackMessage, PreviewId, QuestionId, t.Name, t.SchoolName, PassPort.CurrentUser.UserID, entity.PublishDate.ToString("yyyy-MM-dd")) + "}";
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
        public static string PreviewAdd2(string Question, string PreviewId, long ChapterId, string QuestionId, int ClassId)
        {
            bool boolIsSucess = true;
            string strBackMessage = string.Empty;
            TS_Preview_Entity entity = new TS_Preview_Entity();
            TS_User_Teacher_Entity t = new TS_User_Teacher_Entity();
            if (PassPort.IsAuthenticated)
            {
                try
                {
                    Dictionary<string, object> dict = new Dictionary<string, object>();
                    dict.Add("TeachId", PassPort.CurrentUser.UserID);
                    dict.Add("ClassId", ClassId);
                    dict.Add("ChapterId", ChapterId);

                    TS_TeachMaterials_Chapter_Entity tc = TS_TeachMaterials_Chapter_Logic.TS_TeachMaterials_Chapter_View(ChapterId);
                    int refCount = 0;
                    if (string.IsNullOrEmpty(QuestionId))//发布，非引用
                    {
                        TS_Question_Entity q = TS_Question_Logic.TS_Question_ViewByQuestion(Question);//根据发布问题查看该问题是否发布过
                        if (q == null)//未发布
                        {
                            q = TS_Question_Logic.TS_Question_Add(new TS_Question_Entity()//发布该问题
                            {
                                QuestionId = Guid.NewGuid(),
                                ChapterId = ChapterId,
                                CourseId = tc.CourseId,
                                MaterialsId = tc.MaterialsId,
                                Question = Question,
                                QuestionType = 2
                            });
                        }
                        else//问题已发布
                        {
                            dict["QuestionId"] = q.QuestionId.Value;
                            TS_Preview_Entity p = TS_Preview_Logic.TS_Question_IsPreviewPublish2(dict);//该问题是否由此教师在此章节发布
                            if (p != null)
                            {
                                throw new Exception("您已经发布了");
                            }
                            //else
                            //{
                            //    PreviewId = TS_Preview_Logic.TS_Question_GetFirstPreviewByQuestionId(q.QuestionId.Value);//发布该问题,引用的前概念Id为此问题Id且未被引用过的
                            //}
                        }
                        QuestionId = q.QuestionId.Value.ToString();
                    }
                    else//引用前概念，即问题已存在
                    {
                        dict["QuestionId"] = new Guid(QuestionId);
                        TS_Preview_Entity p = TS_Preview_Logic.TS_Question_IsPreviewPublish2(dict);//该问题是否由此教师在此章节当前班发布，如发布直接返回错误，不添加其他班级的发布
                        if (p != null)
                        {
                            throw new Exception("您已经发布了");
                        }
                    }

                    if (!string.IsNullOrEmpty(PreviewId))//更新引用次数
                    {
                        TS_Preview_Entity p = TS_Preview_Logic.TS_Preview_View(new Guid(PreviewId));
                        refCount = p.ReferenceCount;

                        p.ReferenceCount = p.ReferenceCount + 1;
                        TS_Preview_Logic.TS_Preview_Update(p);
                    }

                    t = TS_User_Teacher_Logic.TS_User_Teacher_View(PassPort.CurrentUser.UserID).First();

                    List<TS_Class_Entity> Classes = TS_Class_Logic.TS_Class_GetClassesByUserId(PassPort.CurrentUser.UserID);
                    Guid batch = Guid.NewGuid();

                    string strClass = "";
                    foreach (TS_Class_Entity ce in Classes)
                    {
                        strClass += ce.Idx + ",";
                    }

                    Guid NewId = Guid.NewGuid();
                    entity = TS_Preview_Logic.TS_Preview_Add(new TS_Preview_Entity()
                    {
                        PreviewId = NewId,
                        ChapterId = ChapterId,
                        ClassIds = strClass,
                        CourseId = tc.CourseId,
                        MaterialsId = tc.MaterialsId,
                        PublishDate = DateTime.Now,
                        Question = Question,
                        QuestionId = new Guid(QuestionId),
                        ReferenceCount = 0,
                        SchoolId = t.SchoolId,
                        TeachId = PassPort.CurrentUser.UserID,
                        RefBy = string.IsNullOrEmpty(PreviewId) ? NewId : new Guid(PreviewId),
                        Batch = batch
                    });

                    PreviewId = entity.PreviewId.Value.ToString();
                }
                catch (Exception ex)
                {
                    boolIsSucess = false;
                    strBackMessage = ex.Message.Replace("\r", "").Replace("\n", "");
                }
            }
            else
            {
                boolIsSucess = false;
                strBackMessage = "您已经登录超时，请重新登录系统。";
            }
            return "{" + string.Format("IsSuccess:{0},Msg:'{1}',PreviewId:'{2}',QuestionId:'{3}',Name:'{4}',SchoolName:'{5}',TeachId:'{6}',PublishSmallDate:'{7}'", boolIsSucess.ToString().ToLower(), strBackMessage, PreviewId, QuestionId, t.Name, t.SchoolName, PassPort.CurrentUser.UserID, entity.PublishDate.ToString("yyyy-MM-dd")) + "}";
        }
    }
}